package com.atos.optical.service.impl;

import cn.hutool.core.util.StrUtil;
import com.atos.optical.common.BaseServiceImpl;
import com.atos.optical.common.ServiceException;
import com.atos.optical.mapper.SysCustomerInfoMapper;
import com.atos.optical.model.po.SysCustomerInfo;
import com.atos.optical.model.query.SysCustomerInfoQuery;
import com.atos.optical.service.SysCustomerInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/14
 */
@Slf4j
@Service
public class SysCustomerInfoServiceImpl extends BaseServiceImpl<SysCustomerInfoMapper,
        SysCustomerInfo> implements SysCustomerInfoService {
    @Autowired
    private SysCustomerInfoMapper mapper;

    @Override
    public boolean save(SysCustomerInfo entity) {
        check(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(SysCustomerInfo entity) {
        check(entity);
        return super.updateById(entity);
    }

    @Override
    public SysCustomerInfoQuery pageByQuery(SysCustomerInfoQuery query) {
        query.setOrders(OrderItem.descs("CREATE_TIME", "MODIFY_TIME"));
        mapper.pageByQuery(query);
        return query;
    }

    private void check(SysCustomerInfo entity) {
        if (isExistCustomerName(entity)) {
            throw new ServiceException("客户名称重复！");
        }
    }

    private boolean isExistCustomerName(SysCustomerInfo entity) {
        QueryWrapper<SysCustomerInfo> query = new QueryWrapper<>();
        query.lambda().ne(StrUtil.isNotBlank(entity.getCustomerId()), SysCustomerInfo::getCustomerId, entity.getCustomerId())
                .eq(SysCustomerInfo::getCustomerName, entity.getCustomerName());
        return 0 < mapper.selectCount(query);
    }
}
